<!--


<script setup>
import { User, Lock, View, Hide, Message, Phone } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { ElMessage } from "element-plus"
import { useRouter } from 'vue-router'
import userApi from "@/api/user.js";

const router = useRouter()

// 表单数据
const user = ref({
  name: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: ''
})

// 表单校验规则
const rules = ref({
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 16, message: '用户名长度必须为 5~16 位', trigger: 'blur' },
    {
      // ✅ 异步校验用户名是否重复
      validator: async (rule, value) => {
        if (!value) {
          return Promise.reject(new Error('请输入用户名'))
        }

        // 记录发出请求时的值，避免结果延迟回来时用户已修改
        const checkedName = value

        try {
          const res = await userApi.selectAll({ name: value })
          console.log('用户名校验返回：', res)

          if (!res || res.code !== 0) {
            return Promise.reject(new Error(res?.msg || '校验失败，请稍后重试'))
          }

          // 如果用户在请求返回前改了输入，忽略这次结果
          if (user.value.name !== checkedName) {
            return Promise.resolve()
          }

          // 接口返回数组，检查是否有重名
          const exists = Array.isArray(res.data)
              ? res.data.some(item => item?.name === checkedName)
              : false

          if (exists) {
            return Promise.reject(new Error('用户名重复，请换一个'))
          }
          return Promise.resolve()
        } catch (err) {
          console.error('用户名校验出错：', err)
          return Promise.reject(new Error('校验失败，请稍后重试'))
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 16, message: '密码长度必须为 3~16 位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== user.value.password) {
          callback(new Error('两次密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ]
})

// 控制密码可见
const showPassword = ref(false)
const showConfirmPassword = ref(false)

// 按钮动画
const isPressed = ref(false)

// 注册逻辑
const register = () => {
  isPressed.value = true
  userApi.add(user.value).then(result => {
    if (result.code == 0) {
      ElMessage.success(result.msg ? result.msg : '注册成功，请登录')
      router.push('/user-login')
    } else {
      ElMessage.error(result.msg)
    }
  })
}

// 去登录
const goLogin = () => {
  router.push('/user-login')
}
</script>

<template>
  <div class="login-bg">
    <el-form
        class="form-login"
        ref="form"
        size="large"
        autocomplete="off"
        :model="user"
        :rules="rules"
        @submit.native.prevent="register"
    >
      <el-form-item>
        <h1>用户注册</h1>
      </el-form-item>

      &lt;!&ndash; 用户名 &ndash;&gt;
      <el-form-item prop="name">
        <el-input
            :prefix-icon="User"
            placeholder="请输入用户名"
            v-model="user.name"
        />
      </el-form-item>

      &lt;!&ndash; 密码 &ndash;&gt;
      <el-form-item prop="password">
        <el-input
            :prefix-icon="Lock"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码"
            v-model="user.password"
        >
          <template #suffix>
            <el-icon class="eye-icon" @click="showPassword = !showPassword">
              <component :is="showPassword ? View : Hide" />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      &lt;!&ndash; 确认密码 &ndash;&gt;
      <el-form-item prop="confirmPassword">
        <el-input
            :prefix-icon="Lock"
            :type="showConfirmPassword ? 'text' : 'password'"
            placeholder="请再次输入密码"
            v-model="user.confirmPassword"
        >
          <template #suffix>
            <el-icon class="eye-icon" @click="showConfirmPassword = !showConfirmPassword">
              <component :is="showConfirmPassword ? View : Hide" />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      &lt;!&ndash; 手机号 &ndash;&gt;
      <el-form-item prop="phone">
        <el-input
            :prefix-icon="Phone"
            placeholder="请输入手机号"
            v-model="user.phone"
        />
      </el-form-item>

      &lt;!&ndash; 邮箱 &ndash;&gt;
      <el-form-item prop="email">
        <el-input
            :prefix-icon="Message"
            placeholder="请输入邮箱"
            v-model="user.email"
        />
      </el-form-item>

      &lt;!&ndash; 已有账号去登录 &ndash;&gt;
      <el-form-item>
        <el-link
            type="primary"
            :underline="false"
            @click="goLogin"
        >
          已有账号？去登录
        </el-link>
      </el-form-item>

      &lt;!&ndash; 注册按钮 &ndash;&gt;
      <el-form-item>
        <el-button
            class="button"
            type="primary"
            auto-insert-space
            native-type="submit"
            @animationend="isPressed = false"
            :class="{ pressed: isPressed }"
        >
          注册
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<style scoped>
.login-bg {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url('@/assets/zhuce.jpg') no-repeat center center / cover;
}
.form-login {
  width: 380px;
  padding: 40px 30px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(12px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  text-align: center;
}
.form-login h1 {
  font-size: 28px;
  margin-bottom: 25px;
  font-weight: bold;
  background: linear-gradient(90deg, #4facfe, #00f2fe);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
.el-input {
  border-radius: 10px;
}
.eye-icon {
  cursor: pointer;
  font-size: 18px;
  color: #666;
}
.eye-icon:hover {
  color: #4facfe;
}
.button {
  width: 100%;
  height: 45px;
  border-radius: 10px;
  background: linear-gradient(90deg, #4facfe, #00f2fe);
  border: none;
  font-size: 16px;
  font-weight: bold;
  color: #fff;
}
.button:hover {
  transform: translateY(-2px) scale(1.02);
  box-shadow: 0 4px 15px rgba(79, 172, 254, 0.6);
}
.button.pressed {
  animation: pressEffect 0.2s ease;
}
@keyframes pressEffect {
  0% { transform: scale(1); }
  50% { transform: scale(0.95); }
  100% { transform: scale(1); }
}
</style>

-->

<script setup>
import { User, Lock, View, Hide, Message, Phone } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { ElMessage } from "element-plus"
import { useRouter } from 'vue-router'
import userApi from "@/api/user.js";

const router = useRouter()

// 表单数据
const user = ref({
  name: '',
  password: '',
  confirmPassword: '',
  phone: '',
  email: ''
})

// 表单校验规则
const rules = ref({
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 16, message: '用户名长度必须为 3~16 位', trigger: 'blur' },
    {
      validator: async (rule, value) => {
        if (!value) return Promise.reject(new Error('请输入用户名'))
        const checkedName = value
        try {
          const res = await userApi.selectAll({ name: value })
          if (!res || res.code !== 0) return Promise.reject(new Error(res?.msg || '校验失败，请稍后重试'))
          if (user.value.name !== checkedName) return Promise.resolve()
          const exists = Array.isArray(res.data) ? res.data.some(item => item?.name === checkedName) : false
          if (exists) return Promise.reject(new Error('用户名重复，请换一个'))
          return Promise.resolve()
        } catch (err) {
          return Promise.reject(new Error('校验失败，请稍后重试'))
        }
      },
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 16, message: '密码长度必须为 3~16 位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== user.value.password) callback(new Error('两次密码不一致'))
        else callback()
      },
      trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ]
})

// 控制密码可见
const showPassword = ref(false)
const showConfirmPassword = ref(false)

// 按钮动画
const isPressed = ref(false)

// 表单 ref
const formRef = ref(null)

// 注册逻辑
const register = async () => {
  try {
    // 触发表单校验，包括异步校验
    await formRef.value.validate()
    isPressed.value = true
    const result = await userApi.add(user.value)
    if (result.code === 0) {
      ElMessage.success(result.msg || '注册成功，请登录')
      router.push('/user-login')
    } else {
      ElMessage.error(result.msg || '注册失败')
    }
  } catch (err) {
    // 校验未通过会进入这里
    ElMessage.error('请先修正表单中的错误')
  }
}

// 去登录
const goLogin = () => {
  router.push('/user-login')
}
</script>

<template>
  <div class="login-bg">
    <el-form
        class="form-login"
        ref="formRef"
        size="large"
        autocomplete="off"
        :model="user"
        :rules="rules"
        @submit.native.prevent="register"
    >
      <el-form-item>
        <h1>用户注册</h1>
      </el-form-item>

      <!-- 用户名 -->
      <el-form-item prop="name">
        <el-input
            :prefix-icon="User"
            placeholder="请输入用户名"
            v-model="user.name"
        />
      </el-form-item>

      <!-- 密码 -->
      <el-form-item prop="password">
        <el-input
            :prefix-icon="Lock"
            :type="showPassword ? 'text' : 'password'"
            placeholder="请输入密码"
            v-model="user.password"
        >
          <template #suffix>
            <el-icon class="eye-icon" @click="showPassword = !showPassword">
              <component :is="showPassword ? View : Hide" />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- 确认密码 -->
      <el-form-item prop="confirmPassword">
        <el-input
            :prefix-icon="Lock"
            :type="showConfirmPassword ? 'text' : 'password'"
            placeholder="请再次输入密码"
            v-model="user.confirmPassword"
        >
          <template #suffix>
            <el-icon class="eye-icon" @click="showConfirmPassword = !showConfirmPassword">
              <component :is="showConfirmPassword ? View : Hide" />
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <!-- 手机号 -->
      <el-form-item prop="phone">
        <el-input
            :prefix-icon="Phone"
            placeholder="请输入手机号"
            v-model="user.phone"
        />
      </el-form-item>

      <!-- 邮箱 -->
      <el-form-item prop="email">
        <el-input
            :prefix-icon="Message"
            placeholder="请输入邮箱"
            v-model="user.email"
        />
      </el-form-item>

      <!-- 已有账号去登录 -->
      <el-form-item>
        <el-link
            type="primary"
            :underline="false"
            @click="goLogin"
        >
          已有账号？去登录
        </el-link>
      </el-form-item>

      <!-- 注册按钮 -->
      <el-form-item>
        <el-button
            class="button"
            type="primary"
            auto-insert-space
            native-type="submit"
            @animationend="isPressed = false"
            :class="{ pressed: isPressed }"
        >
          注册
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.login-bg {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: url('@/assets/zhuce.jpg') no-repeat center center / cover;
}
.form-login {
  width: 380px;
  padding: 40px 30px;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(12px);
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  text-align: center;
}
.form-login h1 {
  font-size: 28px;
  margin-bottom: 25px;
  font-weight: bold;
  background: linear-gradient(90deg, #4facfe, #00f2fe);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}
.el-input {
  border-radius: 10px;
}
.eye-icon {
  cursor: pointer;
  font-size: 18px;
  color: #666;
}
.eye-icon:hover {
  color: #4facfe;
}
.button {
  width: 100%;
  height: 45px;
  border-radius: 10px;
  background: linear-gradient(90deg, #4facfe, #00f2fe);
  border: none;
  font-size: 16px;
  font-weight: bold;
  color: #fff;
}
.button:hover {
  transform: translateY(-2px) scale(1.02);
  box-shadow: 0 4px 15px rgba(79, 172, 254, 0.6);
}
.button.pressed {
  animation: pressEffect 0.2s ease;
}
@keyframes pressEffect {
  0% { transform: scale(1); }
  50% { transform: scale(0.95); }
  100% { transform: scale(1); }
}
</style>
